﻿using hCommand;
using System;
using System.Collections.Generic;
using System.Data;

namespace Persistence {
    public class CsdOutEngine : GkTransaction {
        public long id;
 
        protected override TransRes Execute() {

            CoreStockDet csd = getById<CoreStockDet>(id);
            if (csd == null) {
                return new TransRes("明细不存在" + id);
            }
           
            if (csd.doiDetId > 0) {
                WhDooDet det = getById<WhDooDet>(csd.doiDetId);
                if (det != null) {
                    return updataStatus(csd, StockDetailStatus.单据手动出库);
                } else {
                    WhDopk pk = getById<WhDopk>(csd.doiDetId);
                    if (pk == null) {
                        return new TransRes("出库单据异常");
                    } else {
                        return new TransRes("盘库中");//StockDetailStatus.单据盘亏出库
                    }

                }
           
            } else {
            
                if (csd.status == (int)StockDetailStatus.编辑) {
                    return updataStatus( csd,StockDetailStatus.直接编辑出库 ); 
                } else if (csd.status == (int)StockDetailStatus.库外) {
                    return updataStatus(csd, StockDetailStatus.直接库外出库); 
                } else if (csd.status == (int)StockDetailStatus.库存) {
                    return updataStatus(csd, StockDetailStatus.直接库存出库); 
                }

            }
            return new TransRes(); 
        }

        TransRes updataStatus(CoreStockDet csd, StockDetailStatus s) {
            String sql = "update core_stock_det set out_time=sgj_get_sys_now and status=@status where id=@id";
            exec(sql, new { csd.id, status = (int)s });
            if (StockDetailStatus.直接编辑出库 != s) {
                String checkSql = "select count(*) from core_stock_det  where  status>=0 and pid =@pid   ";
                int res = queryUnique<int>(checkSql, csd);
                if (res == 0) {
                    string sql2 = @"UPDATE  core_stock SET status =@status WHERE id=@stockId";
                    exec(sql2, new { stockId = csd.pid, status = (int)StockStatus.明细出库同步删除 });
                } else {
                    StatUtil.stock(this, csd.pid);
                }
                if (StockDetailStatus.单据手动出库 == s) {
                    StatUtil.cvCSDOut(this, new List<CoreStockDet>() { csd });
                }
                StatUtil.changeBatch(this, new List<CoreStockDet>() { csd });
            } 
            
            return new TransRes(true,s.ToString());
        }
    }
}
